
package com.jy.service.impl;

import com.jy.common.UUIDUtils;
import com.jy.dao.CopeCreditDao;
import com.jy.model.*;
import com.jy.service.AppBaseService;
import com.jy.service.CopeCreditService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/7/6 0006.
 */
@Component
public class CopeCreditServiceImpl implements CopeCreditService {
    @Resource
    private CopeCreditDao cpd;
    @Resource
    private AppBaseService appBaseService;
    //增加流程
    public boolean insertCopeApply(CopeCredit mm, String realname, String dbUser, String dbnames){
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//当前时间
        String apply_time=dateFormat.format(now);
        mm.setApply_time(apply_time);
        ProcessInstance processInstance = appBaseService.startProcessInstance(
                "inputUser", mm.getApply_man(), "MoneyManage",
                mm.getId());
        if (processInstance != null) {
            System.out.println("启动应付授信流程成功");
        }

        // 讲流程ID放入自定义表单
        mm.setProcessId(processInstance.getId());
        int a = cpd.insertCopeApply(mm);
        // 获取任务id
        String taskId = cpd.getTaskId(processInstance.getId());
        // 修改历史任务里的owner改为当前用户
        int b = cpd.updateOwner(realname, taskId);
        //发起流程
        //流程轨迹中增加记录
        Map<String,Object> variables=new HashMap<String, Object>();
        //if(mm.getTypes().equals("0")||mm.getTypes().equals("2")){
        variables.put("message","事业部");

        String dbname = dbnames.substring(0, dbnames.indexOf("--"));
        CopeCredit mms = new CopeCredit();
        mms.setSybcwzj(dbname);
        mms.setId(mm.getId());
        if (mm.getSybcwzj() != "" && mm.getSybcwzj() != null) {
            int aa = cpd.updateSHR(mms);
        }
			/*}else {
				variables.put("message","行业中心");
			}*/
        variables.put("nextUser",dbUser);
        this.updateState(processInstance.getId(), variables, mm.getId(), dbUser, dbUser,mm.getApply_time(),realname);
			/*
			String btnName="提交申请";
			//如果有最大时间，把最大时间赋给操作时间，如果没有，把记录的创建时间赋给操作时间

			MoneyGuiJi og = liuchengguiji(mm.getId,realname,processInstance.getId(),null,
						mm.getApply_time(), btnName);*/



        //	boolean flag2=mmService.updateState(processInstance.getId(),variables, mm.getId(), dbUser, dbUser);
        return a > 0 && b > 0;

    }


    /**
     * @param id
     * @return 发起---提交请假申请 将状态改为1（审核中） pocessId 流程实例id id 主键id dbUser 下一执行人
     *
     */
    public boolean updateState(String pocessId,Map<String, Object> variables, String id,
                               String dbUser, String realname,String cl_time,String realname2) {
        // 结束当前任务进入下一任务，并指定下一执行人（给nextUser赋值为dbUser）；如果流程实例为空则流程实例结束，否则没有结束
        ProcessInstance pi = appBaseService.applyComplete(pocessId, variables);
        int a =cpd.updateStatus(id, 1);
        int a2 =cpd.updateStatus3(id, "0");
        // 获取任务id
        String taskId = cpd.getTaskId(pocessId);
        // 修改历史任务里的owner改为当前用户

        int b = cpd.updateOwner(realname, taskId);

        //流程轨迹中增加记录

        String cl_times=cpd.maxCreateTime(id);
        String btnName="提交申请";
        //如果有最大时间，把最大时间赋给操作时间，如果没有，把记录的创建时间赋给操作时间
        if(cl_times!=null) {
            CopeGuiJi og = liuchengguiji(id, realname2, pocessId, null,
                    cl_times, btnName);
        }else{
            CopeGuiJi og = liuchengguiji(id, realname2, pocessId, null,
                    cl_time, btnName);
        }
        return a > 0 && b > 0;
    }

    private CopeGuiJi liuchengguiji(String id,String userId,String process_id, String commons, String cl_time,String btnName) {

        //String dbUser = (String) variables.get("nextUser");
        String deptIds  = cpd.searchDepartmentId(userId);//根据员工ID得到部门ID，用于权限控制
        /**
         * 添加历史表数据
         * 流程审核轨迹
         */
        CopeGuiJi mg = new CopeGuiJi();
        mg.setId(UUIDUtils.getUUID());//流程轨迹Id
        mg.setProcess_id(process_id);//流程ID
        mg.setDepartment_id(deptIds);//审核人所在部门ID
        mg.setUser_id(userId);//审核人用户ＩＤ
        //根据员工id，得到员工的权限
        List<CopeGuiJi> mgj = cpd.searchRoleName(userId);
        String str="";
        for(CopeGuiJi mgs:mgj){
            System.out.print(mgs.getRoleName());
            str=mgs.getRoleName()+","+str;
        }
        mg.setRoleid(str);//权限名称
        mg.setRealName(mgj.get(0).getRealName());
        mg.setDeptName(mgj.get(0).getDeptName()+"--"+mgj.get(0).getDeptName1()+"--"+mgj.get(0).getDeptName2());
        mg.setCl_time(cl_time);//操作时间
        mg.setComment(commons);//审核意见
        mg.setCopeId(id);

        if(btnName.equals("驳回")){
            mg.setApply_status(1);//0:转到下一人 1:驳回
            mg.setStatus(1);//0:是  1：否
        }else if(btnName.equals("通过")){
            mg.setApply_status(0);//0:转到下一人
            mg.setStatus(0);//0:是  1：否
        }else if(btnName.equals("提交申请")){
            mg.setApply_status(3);//提交申请
            mg.setStatus(0);//0:是  1：否
        }else if(btnName.equals("撤销")){
            mg.setApply_status(4);//撤销
            mg.setStatus(0);//0:是  1：否
        }
        cpd.insertCopeGuiJi(mg);//保存轨迹
        return mg;
    }






    /**
     * 查询部门名称
     * @param id
     * @return
     */
    public Department searchdept(String id){
        return cpd.searchdept(id);
    }
    //查用户
    public User user(String id){
        return cpd.user(id);
    }
    //保存文件
    public  int saveFilename(List<CopeFile> list){
        return cpd.saveFilename(list);
    }

    //查询待审核信息
    public  List<CopeCredit> getTaskCredit(Integer state, Integer size, String token){
      return cpd.getTaskCredit(state,size,token);
    }
    public MoneyManage getsingTaskCredit(String id){
        return cpd.getsingTaskCredit(id);
    }
    public List<Comment> getCommentInfo(String processId){
        return cpd.getCommentInfo(processId);
    }
    public int updatePass(CopeCredit mm,String userId,String pocessId, Map<String, Object> variables,
                          String commons, String id, String tjuser, String btnName,
                          String realname,String cl_time){
        ProcessInstance pi = appBaseService.applyComplete(pocessId, variables,
                commons, tjuser, btnName);
        // 获取任务id
        String taskId =cpd.getTaskId(pocessId);

        // 修改历史任务里的owner改为当前用户
        int b =cpd.updateOwner(realname, taskId);
   /*     if(realname!=null && !realname.equals("")){
            int d =cpd.updateOwner1(realname,pocessId);
        }*/
        String cl_times=cpd.maxCreateTime(id);
        CopeGuiJi og = liuchengguiji(id,userId,pocessId, commons,
                cl_times, btnName);
        int fag = 0;
        fag =cpd.updateStatus2(mm);
        cpd.updateStatus3(id, "1");
        return fag;
    }


    /**
     * 查询名称
     * @param pocessId
     * @return
     */
    public String searchName(String pocessId) {
        // TODO Auto-generated method stub
        return cpd.searchName(pocessId);
    }

    //我的申请信息

    public List<CopeCredit> creditList(Integer rows, Integer page, String token) {
        return cpd.creditList(rows,page,token);
    }

    public CopeCredit getsingCreditApplyInfo(String id){
        return cpd.getsingCreditApplyInfo(id);
    }

    public List<Comment> getComment(String processId){
        return cpd.getComment(processId);
    }
    //轨迹明细列表
//轨迹明细列表
    public List<CopeGuiJi> getLiuChengGuiJi(Integer rows, Integer page,String proId){
        return cpd.getLiuChengGuiJi(rows,page,proId);
    }
    public List<CopeCredit> guiJiList(Integer state, Integer size, String token) {
        return cpd.guiJiList(state,size,token);
    }
    @Override
    public CopeCredit getsingGuiJi(String id) {
        return cpd.getsingGuiJi(id);
    }
    public List<CopeCredit> getBh(String name,String userId){
        return cpd.getBh(name,userId);
    }
    public CopeCredit getBh2(String name){
        return cpd.getBh2(name);
    }
    public MoneyManage getBh3(String name){
        return cpd.getBh3(name);
    }
    public  List <CopeFile>getImgS(String coreId){
        return cpd.getImgS(coreId);
    }

    /**
     * 撤销流程
     * @param id
     * @param process_id
     * @return
     */
    public int iscx(String id, String process_id,String realname,String userId) {
        appBaseService.deleteProcessInstance(process_id, "");
        cpd.updateExecution(process_id,id+"-"+process_id);
        ProcessInstance processInstance =appBaseService.startProcessInstance("inputUser",realname, "MoneyManage",id);
        process_id=processInstance.getId();
        CopeCredit mm = cpd.searchId(id);
        String iscx="1";
        String aduit_state="0";
        int i=cpd.updateCXLC(id,processInstance.getId(),iscx,aduit_state);
        String btnName="撤销";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String time = df.format(new Date());
        liuchengguiji(id,userId,process_id,"",time,btnName);

        return i;
    }


 /*   *//**
     * @param id
     * @return 发起---提交请假申请 将状态改为1（审核中） pocessId 流程实例id id 主键id dbUser 下一执行人
     *
     *//*
    public boolean updateState(String pocessId,Map<String, Object> variables, String id,
                               String dbUser, String realname,String cl_time,String realname2) {
        // 结束当前任务进入下一任务，并指定下一执行人（给nextUser赋值为dbUser）；如果流程实例为空则流程实例结束，否则没有结束
        ProcessInstance pi = appBaseService.applyComplete(pocessId, variables);
        int a =cpd.updateStatus(id, 1);
        int a2 =cpd.updateStatus3(id, "0");
        // 获取任务id
        String taskId = cpd.getTaskId(pocessId);
        // 修改历史任务里的owner改为当前用户

        int b = cpd.updateOwner(realname, taskId);

        //流程轨迹中增加记录

        String cl_times=cpd.maxCreateTime(id);
        String btnName="提交申请";
        //如果有最大时间，把最大时间赋给操作时间，如果没有，把记录的创建时间赋给操作时间
        if(cl_times!=null) {
            CopeGuiJi og = liuchengguiji(id, realname2, pocessId, null,
                    cl_times, btnName);
        }else{
            CopeGuiJi og = liuchengguiji(id, realname2, pocessId, null,
                    cl_time, btnName);
        }
        return a > 0 && b > 0;
    }
*/

    public MoneyManage getBh4(String name,String date) {
        // TODO Auto-generated method stub
        return cpd.getBh4(name,date);
    }

    public MoneyManage getBh5(String name, String date) {
        // TODO Auto-generated method stub
        return cpd.getBh5(name, date);
    }

    public MoneyManage getBh6(String name, String date) {
        // TODO Auto-generated method stub
        return cpd.getBh6(name, date);
    }

    /**
     * 添加前的查询
     * @param mm
     * @return
     */
    public List<CopeCredit> searchApply(CopeCredit mm) {
        // TODO Auto-generated method stub
        return cpd.searchApply(mm);
    }
}
